﻿using SmallJob.Model;
using SmallJob.Services.Code;
using SmallJob.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;

namespace BackEnd.Controllers
{
     [Authorize]
    public class BannerController : Controller
    {
        private readonly IBannerService _BannerService;
        public BannerController(IBannerService BannerService)
        {
            _BannerService = BannerService;
        }
        //
        // GET: /Banner/

        public ActionResult Index(string page, string filter)
        {
            if (string.IsNullOrWhiteSpace(page))
            {
                page = "1";
            }
            ViewData["tableindex"] = new { page = page, pagesize = Convert.ToInt32(Resources.Resource.ItemPerPage), filter = filter };
            return View();
        }
        public ActionResult ConfigBanner()
        {
            var model = _BannerService.GetAllBannerUse();
            return View(model);
        }
        [HttpPost]
        public ActionResult SaveConfigBanner()
        {
            var data = Request.Form.AllKeys;
            foreach (var item in data)
            {
                if (item.Contains("banner-"))
                {

                    try
                    {
                        var id = Convert.ToInt32(item.Substring("banner-".Length));
                        var displaynumber = Convert.ToInt32(Request.Form["banner-" + id]);
                        var banner = _BannerService.GetById(id);
                        banner.DisplayNumber = displaynumber;
                        _BannerService.Update(banner);
                        
                    }
                    catch (Exception)
                    {

                        ModelState.AddModelError("systemerror", "Error");
                    }
                   
                }
            }
            if (ModelState.IsValid)
            {
                ViewData["result"] = "Success";
            }
            var model = _BannerService.GetAllBannerUse();
            return View("ConfigBanner",model);
        }
        public ActionResult Details(int id)
        {
            var model = _BannerService.GetById(id);
            return View(model);
        }
        public ActionResult Add()
        {
            ViewData["isadd"] = true;
            return View("Form");
        }
        public ActionResult Edit(int id)
        {
            ViewData["isadd"] = false;
            var model = _BannerService.GetById(id);
            return View("Form", model);
        }
        public ActionResult Save(HttpPostedFileBase img)
        {


            int id = Convert.ToInt32(Request.Form["id"]);
            var banner = _BannerService.GetById(id);
            bool isadd = false;
            if (banner == null)
            {
                isadd = true;
                banner = new Banner()
                {
                    ID = 0,
                    CreatedDate = DateTime.Now
                };
            }
            if (string.IsNullOrWhiteSpace(Request.Form["title"]))
            {
                ModelState.AddModelError("titleerror", "Title is required");
            }
            else
                banner.Title = Request.Form["title"];
            //banner.IsUse = Convert.ToBoolean(Request.Form["isuse"]);
            banner.Description = Request.Form["descrip"];
            if (ModelState.IsValid && img != null && img.ContentLength != 0)
            {
                DateTime dt = DateTime.Now;
                // extract only the fielname
                var fileName = Path.GetFileName(img.FileName);
                // upload anh vao folder
                var path = Path.Combine(UserUtility.GetFolderBannerUpload(), dt.ToBinary() + "_" + fileName);
                if (!Directory.Exists(UserUtility.GetFolderBannerUpload()))
                {
                    Directory.CreateDirectory(UserUtility.GetFolderBannerUpload());
                }
                img.SaveAs(path);
                WebImage webimg = new WebImage(path);

                if (webimg.Width >= 1350)
                {
                    if (webimg.Height > 430)
                    {
                        webimg.Crop((webimg.Height - 430) / 2, 0, (webimg.Height - 430) / 2, 0);
                    }
                    else
                    {
                        webimg.Resize(webimg.Width, 430, false);
                    }
                    webimg.Save(path);
                    banner.Url = UserUtility.GetImageBannerUpload() + dt.ToBinary() + "_" + fileName;
                }
                else
                {
                    ModelState.AddModelError("imageerror", "Image wrong size!");
                }
                //return Json(UserUtility.GetImageCoverUpload() + u.ID + "/" + dt.ToBinary() + "_" + fileName);
                //provide.ImagePath += "/Uploads/Provide/" + u.ID + "/" + dt.ToBinary() + "_" + fileName + ";";
            }
            else
            {
                ModelState.AddModelError("imageerror", "No Image Selected!");
            }
            banner.ModifiedDate = DateTime.Now;
            if (ModelState.IsValid)
            {
                if (isadd)
                {
                    _BannerService.Add(banner);
                }
                else
                {
                    _BannerService.Update(banner);
                }
                ViewData["isok"] = true;
            }


            ViewData["isadd"] = isadd;
            return View("Form", banner);
        }
        [HttpPost]
        public ActionResult Use(int id)
        {
            try
            {
                var banner = _BannerService.GetById(id);
                banner.IsUse = true;
                _BannerService.Update(banner);
                return Json(true);
            }
            catch (Exception)
            {

                return Json(false);
            }
        }
        [HttpPost]
        public ActionResult NoUse(int id)
        {
            try
            {
                var banner = _BannerService.GetById(id);
                banner.IsUse = false;
                _BannerService.Update(banner);
                return Json(true);
            }
            catch (Exception)
            {

                return Json(false);
            }
        }
        public ActionResult TableBanner(int page, int pagesize, string filter)
        {
            int total = 0;
            pagesize = Convert.ToInt32(Resources.Resource.ItemPerPage);
            if (page == 0)
            {
                page = 1;
            }
            var model = _BannerService.GetByPage(page, pagesize, out total);
            if (!string.IsNullOrWhiteSpace(filter))
            {
                model = _BannerService.GetByPageFilter(page, pagesize, out total, filter);
                ViewData["filter"] = filter;
            }
            if ((total % pagesize) > 0)
            {
                ViewData["total"] = (total / pagesize) + 1;
            }
            else
            {
                ViewData["total"] = total / pagesize;
            }
            ViewData["curpage"] = page;
            ViewData["nextpage"] = page + 1;
            ViewData["prepage"] = page - 1;
            return PartialView(model);
        }

    }
}
